/*
 * Copyright (c) 2022-2023 cetcclout Co., Ltd All rights reserved.
 * Sensor Adapter is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.cetccloud.cimp.adapter;

import com.cetccloud.cimp.adapter.datasource.redis.RedisService;
import com.cetccloud.cimp.adapter.datasource.sqldb.entity.ModelDeviceBindEntity;
import com.cetccloud.cimp.adapter.datasource.sqldb.service.ModelDeviceBindService;
import com.cetccloud.cimp.adapter.handler.DataContextValue;
import com.cetccloud.cimp.adapter.protocol.StartOrStopServerService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * @author
 * @apiNote 初始化配置
 * @date 2022/4/27
 */
@Component
public class AdapterCoreServer implements ApplicationRunner {


	@Autowired
	ModelDeviceBindService deviceBindService;
    @Autowired
    StartOrStopServerService startOrStopServerService;
    @Autowired
    RedisService redisService;

    @Override
    public void run(ApplicationArguments args) throws Exception {

    	//加载设备注册信息到缓存
    	Map<String , Object> map = new HashMap<>();
    	map.put("use_ok","1");
    	List<ModelDeviceBindEntity> l = deviceBindService.listByMap(map);
    	l.forEach(d->{
			if(!redisService.hasKey(String.format(DataContextValue.DEVICE_KEY, d.getDtuId()))) {
				redisService.set(String.format(DataContextValue.DEVICE_KEY, d.getDtuId()), d.getRemark());
			}
    	});
    	
        //缓存中设备列表
        redisService.del(DataContextValue.DTU_STATUS_KEY);

        //初始化需要启动的服务配置集
        startOrStopServerService.initAdapterServer(null);

    }

}
